library ieee;
use IEEE.std_logic_1164.all;

entity mult_beh is
  generic(top : natural := 15);
  port (
    clk : in std_logic;
    nrst : in std_logic;
    a   : in  std_logic_vector (top downto 0);
    b    : in  std_logic_vector (top downto 0);
    product  : out std_logic_vector (2*top+1 downto 0)
  );
end entity mult_beh;

architecture behavior of mult_beh is
  component add_beh
  generic (
    top : integer := 7
  );
  port (
    signal a : in std_logic_vector(top downto 0);
    signal b : in std_logic_vector(top downto 0);
    signal cin : in std_logic;
    signal cout : out std_logic;
    signal sum : out std_logic_vector(top downto 0)
  );
  end component;
  for all : add_beh use entity work.add_beh;

  signal cin : std_logic := '0';
  signal cout : std_logic := '0';
  signal acc : std_logic_vector(2*top+1 downto 0);
  signal sum : std_logic_vector(2*top+1 downto 0);
  signal mand : std_logic_vector(2*top+1 downto 0);
  signal index : integer := 0;
  signal finished : std_logic := '0';
begin

  DUT :add_beh generic map (2*top+1) port map (acc,mand,cin,cout,sum);

  p1 : process (clk, nrst)
    variable mandvar : std_logic_vector(2*top+1 downto 0);
  begin
    if (nrst = '0') then
      acc <= (others => '0');
      index <= 0;
      finished <= '0';
    else
      if  clk'event then
      	if clk = '1' then
        	if index <= top then
          		index <= index + 1;
          		mandvar := (others => '0');
          		if b(index) = '1' then
            		for i in 0 to top loop
              			mandvar(i+index) := a(i);
            		end loop;
          		end if;
        	end if;
        	mand <= mandvar;
        	acc <= sum;
     	else
       		if index > top-1 then
         		finished <= '1';
       		end if;
     	end if;
    end if;
  end process p1;
  p2 : process ( finished)
  begin
    if rising_edge(finished) then
      product <= sum;
    end if;
  end process p2;
end architecture behavior;